package cn.liufuwen.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.dubbo.config.annotation.Reference;
import cn.liufuwen.entity.UserDTO;
import cn.liufuwen.service.UserService;

@Controller
@RequestMapping("/hello")
public class HelloController {
	@Reference(version = "${demo.service.version}")
	UserService userService;
	@RequestMapping("/login")
    public String login() {
        return "login";
    }
	
	@RequestMapping("/dologin")
    public ModelAndView dologin(ModelAndView modelAndView,HttpSession session,UserDTO userDTO) {
		Map<String, Object> map = new HashMap<String, Object>();
		int id =userService.login(userDTO);
		if(id>0){
		  	Date d = new Date();
		  	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			userDTO.setId(id);
			userDTO.setCreateDate(sdf.format(d));
			session.setAttribute("USER_SESSION_KEY", userDTO);
			map.put("CodeNo", 1);
			map.put("Msg", "登录成功");
		}else{
			map.put("CodeNo", 0);
			map.put("Msg", "登录失败");
		}
		modelAndView.addAllObjects(map);
		modelAndView.setViewName("jump");
		return modelAndView;
    }
	@RequestMapping("/register")
    public String register() {
        return "register";
    }
	@RequestMapping("/doregister")
    public ModelAndView doregister(ModelAndView modelAndView,UserDTO userDTO) {
		Map<String, Object> map = new HashMap<String, Object>();
		int id =userService.register(userDTO);
		if(id>0){
			map.put("CodeNo", 2);
			map.put("Msg", "注册成功");
		}else{
			map.put("CodeNo", 0);
			map.put("Msg", "已注册");
		}
		modelAndView.addAllObjects(map);
		modelAndView.setViewName("jump");
		return modelAndView;
    }
	@RequestMapping("/out")
    public ModelAndView out(ModelAndView modelAndView,HttpSession session) {
		session.removeAttribute("USER_SESSION_KEY");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("CodeNo", 3);
		map.put("Msg", "退出成功");
		modelAndView.addAllObjects(map);
		modelAndView.setViewName("jump");
		return modelAndView;
    }
}